﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Photon.SocketServer;
using PhotonHostRuntimeInterfaces;
namespace KylinstarLoginServer
{
    class LoginPeer : ClientPeer
    {
        private static event Action<LoginPeer, EventData, SendParameters> BroadcastMessage;
        public LoginPeer(InitRequest initRequest)
            : base(initRequest)
        {
            BroadcastMessage += OnBroadcastMessage;
        }

        protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
        {
            if (operationRequest.OperationCode == 1) // Chat Custom Operation Code = 1
            {
                // broadcast chat custom event to other peers
                var eventData = new EventData(1) { Parameters = operationRequest.Parameters }; // Chat Custom Event Code = 1
                BroadcastMessage(this, eventData, sendParameters);
                // send operation response (~ACK) back to peer
                var response = new OperationResponse(operationRequest.OperationCode);
                SendOperationResponse(response, sendParameters);
            }
        }

        protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail)
        {
            BroadcastMessage -= OnBroadcastMessage;
        }

        private void OnBroadcastMessage(LoginPeer peer, EventData eventData, SendParameters sendParameters)
        {
            if (peer != this) // do not send chat custom event to peer who called the chat custom operation 
            {
                SendEvent(eventData, sendParameters);
            }
        }
    }
}
